# coding: utf-8

from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QHBoxLayout
from qfluentwidgets import IconWidget, FluentStyleSheet, TransparentToolButton, FluentIcon as FIF, BodyLabel, \
    toggleTheme
from qframelesswindow import TitleBarBase


class CustomTitleBar(TitleBarBase):
    settingClicked = Signal(bool)

    def __init__(self, parent):
        super().__init__(parent)
        self.hBoxLayout = QHBoxLayout(self)
        self.iconLabel = IconWidget(self)
        self.titleLabel = BodyLabel(self)
        self.themeBtn = TransparentToolButton(FIF.CONSTRACT, self)
        self.settingsBtn = TransparentToolButton(FIF.SETTING, self)

        self.iconLabel.setFixedSize(18, 18)
        self.themeBtn.setFixedSize(46, 32)
        self.settingsBtn.setFixedSize(46, 32)
        self.setFixedHeight(48)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.addSpacing(12)
        self.hBoxLayout.addWidget(self.iconLabel)
        self.hBoxLayout.addWidget(self.titleLabel)
        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addWidget(self.themeBtn, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.hBoxLayout.addWidget(self.settingsBtn, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.hBoxLayout.addWidget(self.minBtn, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.hBoxLayout.addWidget(self.maxBtn, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
        self.hBoxLayout.addWidget(self.closeBtn, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)

        self.window().windowIconChanged.connect(self.setIcon)
        self.window().windowTitleChanged.connect(self.setTitle)
        self.themeBtn.clicked.connect(lambda: toggleTheme(save=True))
        self.settingsBtn.clicked.connect(self.settingClicked)

        FluentStyleSheet.FLUENT_WINDOW.apply(self)

    def setTitle(self, title):
        self.titleLabel.setText(title)
        self.titleLabel.adjustSize()

    def setIcon(self, icon):
        self.iconLabel.setIcon(icon)
